package chat

import (
	"cade/src/game/msg"
	Err "cade/src/proto/errorcode"
)

// ============================================================================

const (
	c_MaxRecentRecords  = 50
	c_MaxTextLength     = 500
	c_RoomTimerInterval = 15 // seconds
	c_HotWordsInterval  = 10 // minutes
)

// ============================================================================

var GMs = map[string]bool{
	"admin": true,
	"gm":    true,
	"boss":  true,
}

// ============================================================================

type chat_entry_t struct {
	Sender string
	Text   string
}

// ============================================================================

func GetRoomList() (ret []*msg.ChatRoomInfo) {
	locker.RLock()
	defer locker.RUnlock()

	ret = make([]*msg.ChatRoomInfo, 0, len(rooms))

	for _, rm := range rooms {
		ret = append(ret, &msg.ChatRoomInfo{
			Id:   rm.Id,
			Name: rm.Name,
			Num:  rm.Num,
		})
	}

	return
}

func CreateRoom(plr IPlayer, name string, f func(ec int32)) {
	// dont create if already in a room
	if plr.GetChatroomId() != 0 {
		f(Err.Chat_AlreadyInRoom)
		return
	}

	// check room existance
	rm := find_room_by_name(name)
	if rm != nil {
		f(Err.Chat_RoomExists)
		return
	}

	// create and add
	rm = new_room(name)
	if !add_room(rm) {
		f(Err.Chat_RoomExists)
		return
	}

	// run the room
	rm.run()

	// add the creator
	plr.SetChatroomId(rm.Id)
	rm.Push(func() {
		ec := rm.AddPlayer(plr)
		f(ec)
	})
}

func EnterRoom(plr IPlayer, id int32, f func(ec int32, records []*msg.ChatTextEntry)) {
	// dont enter if already in a room
	if plr.GetChatroomId() != 0 {
		f(Err.Chat_AlreadyInRoom, nil)
		return
	}

	// find the room
	rm := find_room(id)
	if rm == nil {
		f(Err.Chat_RoomNotFound, nil)
		return
	}

	// enter
	plr.SetChatroomId(rm.Id)
	rm.Push(func() {
		ec := rm.AddPlayer(plr)
		if ec != Err.OK {
			f(ec, nil)
			return
		}

		f(Err.OK, rm.tomsg_records())
	})
}

func LeaveRoom(plr IPlayer, f func(int32)) {
	// find player room
	rm := find_room(plr.GetChatroomId())
	if rm == nil {
		f(Err.Chat_NotInTheRoom)
		return
	}

	// leave
	plr.SetChatroomId(0)
	rm.Push(func() {
		ec := rm.RemovePlayer(plr)
		f(ec)
	})
}

func SendText(plr IPlayer, text string, f func(ec int32)) {
	// find player room
	rm := find_room(plr.GetChatroomId())
	if rm == nil {
		f(Err.Chat_NotInTheRoom)
		return
	}

	// send
	rm.Push(func() {
		ec := rm.SendText(plr, text)
		f(ec)
	})
}
